package com.cuitrip.business.home.travel;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.favorite.TravelTrip;
import com.cuitrip.business.home.favorite.ui.FavAnimation;
import com.cuitrip.business.home.recommend.model.RecommendTravelTrip;
import com.cuitrip.business.home.travel.model.FilterExp;
import com.cuitrip.business.home.travel.model.SelectInfo;
import com.cuitrip.business.home.travel.ui.ConditionViewHolder;
import com.cuitrip.business.home.travel.ui.OnSortChangedListener;
import com.cuitrip.business.home.travel.ui.TravelTripHolderView;
import com.cuitrip.business.home.travel.ui.TravelTripListView;
import com.cuitrip.business.home.trip.model.RecommendOutData;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.component.autoload.AutoLoadScrollListener;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ListUtil;
import com.cuitrip.util.text.TextProxy;
import com.cuitrip.util.track.TrackUtil;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.HolderViewAdapter;
import com.lab.adapter.animation.SwingBottomInAnimationAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.image.process.MakeImageUtil;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class TravelTripListFragment extends CustomUiFragment implements SwipeRefreshLayout.OnRefreshListener, Runnable, IProxyCallback, TravelTripListView {

    public static final int RECOMMEND_MODE = 0x01;
    public static final int SEARCH_MODE = 0x02;
    public static final int INFLATE_MODE = 0x03;
    public static final int PAGE_SIZE = 10;
    @Bind(R.id.ct_list)
    ListView mListView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    @Bind(R.id.background)
    ImageView backgroundImage;
    FavAnimation mFavAnimation;
    @Bind(R.id.condition_layout)
    View mConditionLayout;

    private boolean isFiltered = false;

    private SelectInfo selectInfo;

    private ConditionViewHolder mConditionViewHolder;

    private View view;
    private int mCurrentMode = RECOMMEND_MODE;
    private HolderViewAdapter adapter;
    private List<TravelTrip> dataList = new ArrayList<>();
    private int start = 0;

    private int initialMode = RECOMMEND_MODE;

    private ApiProxy mApiProxy = new ApiProxy(this);


    private AutoLoadScrollListener autoLoadScrollListener = new AutoLoadScrollListener(this);
    private RecommendOutData mRecommendOutData;

    public TravelTripListFragment() {
        mCurrentMode = RECOMMEND_MODE;
        initialMode = RECOMMEND_MODE;
    }

    public static TravelTripListFragment newInstance(SelectInfo selectInfo) {
        TravelTripListFragment travelTripListFragment = new TravelTripListFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(SelectInfo.KEY, selectInfo);
        travelTripListFragment.setArguments(bundle);
        return travelTripListFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getArguments() != null) {
            selectInfo = (SelectInfo) getArguments().getSerializable(SelectInfo.KEY);
            if (TextUtils.isEmpty(selectInfo.getKeyWords()) && TextUtils.isEmpty(selectInfo.getCityAbbr())) {
                mCurrentMode = RECOMMEND_MODE;
                initialMode = RECOMMEND_MODE;
            } else {
                mCurrentMode = SEARCH_MODE;
                initialMode = SEARCH_MODE;
            }
        }

        View view = super.onCreateView(inflater, container, savedInstanceState, R.layout.travel_trip_list);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mFavAnimation != null) {
            mFavAnimation.detach();
            mFavAnimation = null;
        }
        mConditionViewHolder.destroy();
        ButterKnife.unbind(this);
    }

    public void initView() {
        initLikeAnimation();
        ButterKnife.bind(this, getView());
        hideRightButton();
        autoLoadScrollListener.setLoadingView(ListUtil.setupLoadingFooter(getHostActivity().getLayoutInflater(), mListView));
        setBottleLineVisibility(false);

        mConditionViewHolder = new ConditionViewHolder(mConditionLayout, this, selectInfo);
        mConditionLayout.setVisibility(View.GONE);
        mConditionViewHolder.setOnSortChangedListener(new OnSortChangedListener() {
            @Override
            public void onChanged(FilterExp.SortInfo sortInfo) {
                refreshTripList(sortInfo);
            }
        });

        adapter = new HolderViewAdapter(getActivity(), dataList, TravelTripHolderView.class);
        adapter.setHolderViewCallback(new HolderViewAdapter.HolderViewCallback() {
            @Override
            public void onHolderViewInvalidate(BaseHolderView holderView, int position) {
                if (holderView instanceof TravelTripHolderView) {
                    TravelTripHolderView cardItemHolderView = (TravelTripHolderView) holderView;
                    cardItemHolderView.setPage(position / PAGE_SIZE);
                    List<String> ids = new ArrayList<>();
                    for (TravelTrip trip : dataList) {
                        ids.add(String.valueOf(trip.getSid()));
                    }
                    cardItemHolderView.setCurrentList(ids);
                }

            }
        });
        SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
        swingBottomInAnimationAdapter.setAbsListView(mListView);
        swingBottomInAnimationAdapter.setAnimationDurationMillis(500);
        mListView.setAdapter(swingBottomInAnimationAdapter);
    }

    /**
     * 初始化收藏动画
     */
    private void initLikeAnimation() {
        if (mFavAnimation == null) {
            mFavAnimation = new FavAnimation(getActivity().getWindow()) {
                @Override
                public int getTextResource() {
                    return R.string.fav_full_icon;
                }
            };
            mFavAnimation.attach();
        }
    }

    private void getSortList() {
        if (start == 0 && !isFiltered) {
            TripBusiness.getSearchNaviParm(mApiProxy);
        }
    }

    public void initData() {
        mStateLayout.changeState(StateLayout.State.Loading);
        refreshTripList(selectInfo.getFilterExp().getSelectSort());
        TrackProxy.getInstance().reviewPage(TrackBusiness.Source.SERVICE_LIST, "");
    }

    public void initListener() {
        refreshLayout.setOnRefreshListener(this);
        mListView.setOnScrollListener(autoLoadScrollListener);
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                changeLoadMode(initialMode);
                refreshTripList(selectInfo.getFilterExp().getSelectSort());
            }

        });


    }


    public void onDestroy() {
        super.onDestroy();
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
    }

    private void inflateList(List<RecommendTravelTrip> tempList) {
        if (start == 0) {
            dataList.clear();
        }
        dataList.addAll(tempList);
        adapter.notifyDataSetChanged();
        if (dataList.isEmpty()) {
            mStateLayout.changeState(StateLayout.State.Empty);
        } else {
            if (start == 0) {
                mListView.setSelection(0);
            }
            mStateLayout.changeState(StateLayout.State.INIT);
        }
        autoLoadScrollListener.setEnable(true);
    }


    private void refreshTripList(FilterExp.SortInfo sortInfo) {
        start = 0;
        if (mCurrentMode == RECOMMEND_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, "", start, PAGE_SIZE, selectInfo.getFrom(), sortInfo.getSearchKey(), selectInfo);
        } else if (mCurrentMode == SEARCH_MODE) {
            if (!selectInfo.isEmpty()) {
                if (!TextUtils.isEmpty(selectInfo.getKeyWords())) {
                    TrackUtil.trackScreenName("/search/results/filtered");
                } else if (!TextUtils.isEmpty(selectInfo.getCityAbbr())) {
                    TrackUtil.trackScreenName("/%s/%s/filtered", "TW", selectInfo.getCityAbbr());
                }
            }
            if (!TextUtils.isEmpty(selectInfo.getCityAbbr())) {
                TrackUtil.trackScreenName("/%s/%s/sort/%S", "TW", selectInfo.getCityAbbr(), sortInfo.getSearchKey());
            }

            TripBusiness.getTravelTripList(mApiProxy, selectInfo.getKeyWords(), start, PAGE_SIZE, selectInfo.getFrom(), sortInfo.getSearchKey(), selectInfo);
        } else {
            TripBusiness.getTravelTripList(mApiProxy,
                    "", start, PAGE_SIZE, selectInfo.getFrom(), sortInfo.getSearchKey(), null);
        }
    }


    @Override
    public void onRefresh() {
        refreshLayout.setRefreshing(true);
        refreshTripList(selectInfo.getFilterExp().getSelectSort());
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }


    @Override
    public void onTopbarRightPress() {
        isFiltered = true;
        mConditionViewHolder.leaveCurrentMode();
        refreshLayout.setRefreshing(true);
        refreshTripList(selectInfo.getFilterExp().getSelectSort());
    }

    private void getItemList(RecommendOutData data) {
        if (data == null) {
            return;
        }
        selectInfo.facetList.addAll(data.getFacetList());
    }

    @Override
    public void onTopbarLeftPress() {
        getHostActivity().finish();
    }


    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        customUiConfig.mTopbarMiddleAreaName = selectInfo.getTitle();
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        customUiConfig.mDisMissTopbarBottomLine = true;
        customUiConfig.mTopbarRightAreaName = getString(R.string.operation_ok_1);

        return customUiConfig;
    }


    public void setBottleLineVisibility(boolean flag) {
        if (!flag) {
            getHostActivity().removeView(R.id.bar_bottom_line);
        }
    }

    @Override
    public void run() {
        autoLoadScrollListener.setEnable(false);
        start = dataList.size();
        autoLoadScrollListener.onLoadChanged(true);
        if (mCurrentMode == RECOMMEND_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, "", start, PAGE_SIZE, selectInfo.getFrom(), selectInfo.getFilterExp().getSelectSort().getSearchKey(), selectInfo);
        } else if (mCurrentMode == SEARCH_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, selectInfo.getKeyWords(), start, PAGE_SIZE, selectInfo.getFrom(), selectInfo.getFilterExp().getSelectSort().getSearchKey(), selectInfo);
        } else if (mCurrentMode == INFLATE_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, "", start, PAGE_SIZE, selectInfo.getFrom(), selectInfo.getFilterExp().getSelectSort().getSearchKey(), selectInfo);
        }
    }

    private void changeLoadMode(int mode) {
        this.mCurrentMode = mode;
    }

    private void handleHeadView() {
        if (mCurrentMode != INFLATE_MODE) {
            mListView.removeHeaderView(view);
            refreshLayout.setEnabled(true);
        } else {
            refreshLayout.setEnabled(false);
        }
    }

    private void handleEmptySearchResult() {
        if (mCurrentMode == SEARCH_MODE && !TextUtils.isEmpty(selectInfo.getKeyWords()) && (selectInfo.isEmpty())) {
            mStateLayout.changeState(StateLayout.State.INIT);
            view = getLayoutInflater(null).inflate(R.layout.headview_trip_list, null);
            IconTextView btnClose = (IconTextView) view.findViewById(R.id.close);
            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListView.removeHeaderView(view);
                }
            });
            mListView.addHeaderView(view);
            changeLoadMode(INFLATE_MODE);
            refreshTripList(selectInfo.getFilterExp().getLikeDescSort());
        } else {
            mStateLayout.changeState(StateLayout.State.Empty);
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()) {
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        refreshLayout.setRefreshing(false);
        //处理行程搜索结果
        if (ApiManager.SERVICE_SEARCH.equals(response.getApiName())) {
            handleHeadView();
            autoLoadScrollListener.onLoadChanged(false);
            //当结果正常，填充list
            if (response.isResponseNormal()) {
                if (response.result instanceof RecommendOutData) {
                    mRecommendOutData = (RecommendOutData) response.result;
                    List<RecommendTravelTrip> list = mRecommendOutData.getLists();
                    inflateList(list);
                    selectInfo.addFacetList(mRecommendOutData.getFacetList());
                    getSortList();
                    if (isFiltered) {
                        mTopbarMiddleArea.setText(TextProxy.getInstance().formatWithSingleAndMore(mRecommendOutData.getViewTotal(), R.string.trip_list_title_one, R.string.trip_list_title_more));
                    } else {
                        mTopbarMiddleArea.setText(selectInfo.getTitle());
                    }
                }
            } else {
                //结果异常时，处理异常页面
                mListView.removeHeaderView(view);
                if (start != 0) {
                    return false;
                }
                //处理无结果页面
                if (response != null && response.code == 201) {
                    handleEmptySearchResult();
                } else {
                    MessageUtils.showToast(response.msg);
                    mStateLayout.changeState(StateLayout.State.NoNetwork);
                }
                mTopbarMiddleArea.setText(selectInfo.getTitle());
            }
        } else if (ApiManager.GET_SEARCH_NAVI_PRAM.equals(response.getApiName())) {
            if (response.isResponseNormal()) {
                if (response.result instanceof FilterExp) {
                    selectInfo.setFilterExp((FilterExp) response.result);
                    if (selectInfo.getFilterExp().getSortListSize() > 0) {
                        selectInfo.getFilterExp().setSelectSortPosition(0);
                    }
                    mConditionLayout.setVisibility(View.VISIBLE);
                }
            } else {
                MessageUtils.showToast(response.msg);
            }
        }
        return false;
    }

    public void showBlurBackground() {
        if (getView() != null && backgroundImage.getVisibility() == View.GONE) {
            Bitmap bitmap = MakeImageUtil.takeScreenShot(getView());
            backgroundImage.setImageBitmap(bitmap);
            backgroundImage.setVisibility(View.VISIBLE);
        }
    }

    public void hideBlurBackground() {
        if (backgroundImage.getVisibility() == View.VISIBLE) {
            backgroundImage.setVisibility(View.GONE);
        }
    }

    @Override
    public void showRightButton() {
        if (mTopbarRightArea.getVisibility() != View.VISIBLE) {
            mTopbarRightArea.setVisibility(View.VISIBLE);
            mTopbarRightArea.setText(R.string.operation_ok_1);
        }
    }

    @Override
    public void hideRightButton() {
        if (mTopbarRightArea.getVisibility() != View.GONE) {
            mTopbarRightArea.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onBackPressed() {
        return mConditionViewHolder.backPress();
    }

    public interface SelectCallback {

        public void onResultBack(SelectInfo selectInfo);

    }

}
